/*
 * @Author: 千锋爱佛僧
 * @公众号: 大前端私房菜
 * @Slogan: 千锋精品教程，好学得不像实力派！
 */
import React, { useEffect, useState } from "react";
import axios from "axios";
import { TMAP_KEY } from "@/config";
import { Button } from "antd";
import { AddressType } from "@/types/pro";
export interface ITencentMapProps {
  handleAddress: (arg: AddressType) => void;
}

export default function TencentMap(props: ITencentMapProps) {
  const TMap = (window as any).TMap;
  let [latlng, setLatLng] = useState<[number, number]>();
  let [address, setAddress] = useState<string>("");
  let [city, setCity] = useState<string>("");
  let [district, setDistrict] = useState<string>("");

  function initMap() {
    //定义地图中心点坐标 ：106.505 纬度：29.5332
    var center = new TMap.LatLng(29.5332, 106.505);
    //定义map变量，调用 TMap.Map() 构造函数创建地图
    var map = new TMap.Map(document.getElementById("container"), {
      center: center, //设置地图中心点坐标
      zoom: 11, //设置地图缩放级别
      // pitch: 43.5, //设置俯仰角
      // rotation: 45, //设置地图旋转角度
    });
    // 创建marker对象
    var marker = new TMap.MultiMarker({
      id: "my-marker",
      map: map,
    });
    map.on("click", (evt: any) => {
      // console.log(evt);
      let { lat, lng } = evt.latLng;
      setLatLng([lat, lng]);
      marker.remove(["marker01"]);
      marker.add({
        id: "marker01",
        position: evt.latLng,
      });
      // 根据经纬度，获取地理位置信息
      let url = `/qqmap/ws/geocoder/v1/?location=${lat},${lng}&key=${TMAP_KEY}&get_poi=1`;
      axios.get(url).then((res) => {
        console.log(res);
        let { address, address_component } = res.data.result;
        let { city, district } = address_component;
        setAddress(address);
        setCity(city);
        setDistrict(district);
        
      });
    });
  }
  const handleDone = () => {
    props.handleAddress({ address, city, district, latlng }); //触发子父通信
  };
  useEffect(() => {
    initMap();
  }, []);
  return (
    <>
      <div>
        {latlng}--{address}
        <Button type="primary" onClick={handleDone}>
          确认选址
        </Button>
      </div>
      <div
        id="container"
        style={{ height: "450px", border: "1px solid red" }}
      ></div>
    </>
  );
}
